# -*- coding: utf-8 -*-
import logging
import queue
import time
from threading import Thread
from wcferry import Wcf
from job_mgmt import Job
from modules.new_friends_module import NewFriendsModule
from modules.response_group_module import ResponseGroupModule
from modules.response_single_module import ResponseSingleModule


class Robot(Job):
    """个性化自己的机器人
    """

    def __init__(self, wcf: Wcf) -> None:
        self.wcf = wcf
        # self.allContacts = self.getAllContacts()
        self.message_queue = queue.Queue()
        # 初始化日志
        logging.basicConfig(level=logging.INFO)
        self.log = logging.getLogger(__name__)
        self.message_modules = [ResponseGroupModule, ResponseSingleModule, NewFriendsModule]

    # 机器人的消息回调函数
    def enableReceivingMsg(self) -> None:
        def innerProcessMsg(wcf: Wcf):
            while wcf.is_receiving_msg():
                try:
                    msg = wcf.get_msg()
                    for modules in self.message_modules:
                        modules().run(msg, wcf)
                except Exception as e:
                    pass
        # 许接收消息，成功后通过 `get_msg` 读取消息
        self.wcf.enable_receiving_msg()
        Thread(target=innerProcessMsg, name="GetMessageThread", args=(self.wcf,), daemon=True).start()

    def getAllContacts(self) -> dict:
        """
        获取联系人（包括好友、公众号、服务号、群成员……）
        格式: {"wxid": "NickName"}
        """
        contacts = self.wcf.query_sql("MicroMsg.db", "SELECT UserName, NickName FROM Contact;")
        return {contact["UserName"]: contact["NickName"] for contact in contacts}

    def keepRunningAndBlockProcess(self) -> None:
        """
        自动调度持续运行
        """
        while True:
            self.runPendingJobs()
            time.sleep(1)

    # 为什么要用获取昵称呢？因为@人时调用wcf.send_text(msg, r, ats)，其中 ats是指群昵称，不是wxid
    def getMsgSender(self, wxids, chat_room):
        contacts = self.wcf.query_sql("MicroMsg.db", "SELECT UserName, NickName FROM Contact;")
        ats = ""
        for wxid in wxids:
            # 这里偷个懒，直接 @昵称。有必要的话可以通过 MicroMsg.db 里的 ChatRoom 表，解析群昵称
            ats += f" @{self.allContacts.get(wxid, '')}"
        return ats
